<?php 
require_once 'db.inc.php';
define("API_KEY", "AIzaSyAF9O4Gr0QrE-2Lqd79TLD-l169U2GjFVA");

function sendUpdateMessage($user_id, $week_years, $origin) {	
	return sendMessage($user_id, $origin, array("type" => "sync_shifts", "week_years" => json_encode($week_years)));	
}

function sendPreferences($user_id, $origin) {
	return sendMessage($user_id, $origin, array("type" => "sync_prefs"));
}

function sendMessage($user_id, $origin, $data) {
	$registrationIDs = getDevices($user_id, $origin);
	if (sizeof($registrationIDs) == 0)
		return;
	
	// Set POST variables
	$url = 'https://android.googleapis.com/gcm/send';
	
	$postdata = array(
			'registration_ids'  => $registrationIDs,
			'data'              => $data,
	);
	
	$headers = array(
			'Authorization: key=' . API_KEY,
			'Content-Type: application/json'
	);
	// Open connection
	$ch = curl_init();
	print_r($postdata);
	// Set the url, number of POST vars, POST data
	curl_setopt( $ch, CURLOPT_URL, $url );
	
	curl_setopt( $ch, CURLOPT_POST, true );
	curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
	
	curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $postdata ) );
	
	// Execute post
	$result = curl_exec($ch);
	
	// Close connection
	curl_close($ch);
	return $result;
}

function getDevices($user_id, $origin) {
	$devices = array();
	$result = mysql_query(sprintf("SELECT regId FROM ".TABLE_PREFIX."devices
			WHERE active = 1 AND user = %d AND deviceId != '%s'",
			$user_id, $origin)) or die(mysql_error());
	while ($row = mysql_fetch_assoc($result)) {
		$devices[] = $row['regId'];
	}
	return $devices;
}

?>